import { useRef, useState } from 'react';
import { Modal, message } from 'antd';
import { ProForm, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { saveKnowledge, saveManagerList } from '@/services/knowledge';

import type { ProFormInstance } from '@ant-design/pro-components';

import styles from './index.less';

const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 18 },
};

interface Props {
  knowledgeVisible: boolean;
  knowledgeDetailInfo?: API.KnowledgeDetail;
  modelTitle: string;
  closeModel: () => void;
}

const KnowledgeDetailModel: React.FC<Props> = (props) => {
  const { knowledgeVisible, knowledgeDetailInfo, modelTitle, closeModel } = props;
  const formRef = useRef<ProFormInstance>();

  // 关闭
  const handleClose = () => {
    formRef.current?.resetFields();
    closeModel();
  };

  // 确定按钮
  const handleAdd = () => {
    formRef.current
      ?.validateFields()
      .then(async (values) => {
        const res = await saveKnowledge({
          id: knowledgeDetailInfo?.id || '',
          name: values.name,
          description: values.description,
        });
        if (!res.code && res.data) {
          message.success('修改成功');
          handleClose();
        }
      })
      .catch(() => {});
  };

  return (
    <div>
      <Modal
        maskClosable={false}
        width={800}
        title={modelTitle}
        open={knowledgeVisible}
        onOk={handleAdd}
        onCancel={handleClose}
      >
        <div style={{ minHeight: '160px' }}>
          <ProForm
            formRef={formRef}
            {...formItemLayout}
            layout="horizontal"
            submitter={false}
            initialValues={{
              name: knowledgeDetailInfo?.name,
              description: knowledgeDetailInfo?.description,
            }}
          >
            <ProFormText
              name="name"
              label="知识库名称"
              placeholder="最多20字符"
              fieldProps={{ maxLength: 20 }}
              rules={[
                {
                  required: true,
                  message: '请输入名称',
                },
                {
                  max: 20,
                  message: '名称长度1-20个字符',
                },
              ]}
            />
            <ProFormTextArea
              name="description"
              label="描述"
              placeholder="最多30字符"
              fieldProps={{ maxLength: 30 }}
            />
          </ProForm>
        </div>
      </Modal>
    </div>
  );
};

export default KnowledgeDetailModel;
